'use client'

import Image from 'next/image'
import {
  Dropdown,
  DropdownTrigger,
  DropdownMenu,
  DropdownItem,
} from '@nextui-org/react'
import { useSearchParams } from 'next/navigation'
import { usePathname } from '@/src/navigation'
import { useRouter } from '@/src/navigation'

import triangleGrayIcon from '@/public/triangle_gray_small.png'
import { useState } from 'react'

interface DropDownProps {
  tag: string
  items: (ProductCategory | Manufacturer | Model)[]
  children: React.ReactNode
}

const DropDownMobile: React.FC<DropDownProps> = (props) => {
  const { tag, items, children } = props

  const searchParams = useSearchParams()
  const pathname = usePathname()
  const router = useRouter()

  const finalItems = () => {
    if (tag === 'category' && items) {
      const initialIndustryId = items[0].id.toString()

      const selectedIndustryId =
        searchParams.get('industry') || initialIndustryId

      const currentCategories = (
        items.find(
          (item) => item.id.toString() === selectedIndustryId
        ) as ProductCategory
      )?.item

      return [{ id: 0, title: 'All' }, ...currentCategories]
    } else {
      return items
    }
  }

  const [selectedId, setSelectedId] = useState<string | null>(null)
  const selectedItem = finalItems().find(
    (item) => item.id.toString() === selectedId
  )

  const handleSelect = (id: string) => {
    setSelectedId(id)

    const params = new URLSearchParams(searchParams)
    if (id === '0') {
      params.delete(tag)
    } else {
      params.set(tag, id)
    }
    router.replace(`${pathname}?${params.toString()}`, { scroll: false })
  }

  return (
    <Dropdown aria-label='drop-down'>
      <DropdownTrigger aria-label='drop-down'>
        <div
          className={`flex justify-between items-center rounded-full text-[0.75rem] leading-[1.1875rem] font-medium p-2 bg-[#F4F4F4] text-[#999999]`}
        >
          {selectedItem ? selectedItem.title : children}
          <div className='w-[0.1875rem]'></div>
          <div className='relative mt-1 w-[0.375rem] h-[0.34375rem]'>
            <Image
              src={triangleGrayIcon}
              alt='dropdown icon'
              fill
              sizes='(max-width: 1024px) 2vw'
            />
          </div>
        </div>
      </DropdownTrigger>
      <DropdownMenu aria-label='drop-down'>
        {finalItems().map((item) => {
          return (
            <DropdownItem
              aria-label='drop-down'
              key={item.id}
              onClick={() => handleSelect(item.id.toString())}
            >
              {item.title}
            </DropdownItem>
          )
        })}
      </DropdownMenu>
    </Dropdown>
  )
}

export default DropDownMobile
